package edu.fiu.cs.kdrg.sql.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;




import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import edu.fiu.cs.kdrg.sql.syntax.tree.Node;
import edu.fiu.cs.kdrg.sql.syntax.tree.NodeType;

public class XTree {
	
	public static void TreeSerialize(Node rootNode,FileOutputStream out) throws IOException{
		Document doc = new Document();
		Element root = recursiveTreeNode(rootNode);
		doc.setRootElement(root);
		XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
		xmlOut.output(root, out);
	}
	
	public static Element recursiveTreeNode(Node node){
		Element element = new Element("node");
		element.setAttribute("name", node.getName());
		element.setAttribute("type",""+node.getType());
		int childrenCount = node.childrenCount();
		for(int i=0;i<childrenCount;i++){
			Element child = recursiveTreeNode(node.getChild(i));
			element.addContent(child);
		}
		return element;
	}

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Node root = new Node();
		root.setName("root");
		root.setType(NodeType.SELECT_STATEMENT);
		Node child1 = new Node();
		child1.setName("child1");
		child1.setType(NodeType.UPDATE_STATEMENT);
		Node child2 = new Node();
		child2.setName("child2");
		child2.setType(NodeType.INSERT_STATEMENT);
		root.addChild(child1);
		root.addChild(child2);
		FileOutputStream out = new FileOutputStream("xtree.xml");
		TreeSerialize(root,out);
		out.close();
	}

}
